package ua.edu.nuos.jeetraining2012.automator.services.bl.services.com;

import ua.edu.nuos.jeetraining2012.automator.core.vo.message.Message;
import ua.edu.nuos.jeetraining2012.automator.core.vo.message.MessageDestination;
import ua.edu.nuos.jeetraining2012.automator.core.vo.message.MessageSource;
import ua.edu.nuos.jeetraining2012.automator.services.bl.common.services.message.AbstractMessageService;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.search.BodyTerm;
import javax.mail.search.SearchTerm;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;

/**
 * Alexandr Dibrivny
 */
public class GmailService extends AbstractMessageService {

    private static final String HOST = "smtp.gmail.com";
    protected Session session;
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    protected boolean isAuthorized() {
        return false;
    }

    @Override
    protected void authorize() {
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.user", username);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        session = Session.getDefaultInstance(props, null);
    }

    @Override
    protected void executeSendMessage(Message message, MessageDestination destination) {
        InternetAddress[] addresses = destination.toAddress();
        try {
            MimeMessage mail = new MimeMessage(session);
            mail.setFrom(new InternetAddress(username));
            mail.setRecipients(MimeMessage.RecipientType.TO, addresses);
            mail.setSubject(message.getSubject());
            mail.setContent("CONTENT", "text/html; charset=utf-8");
            mail.setText(message.getText());
            Transport transport = session.getTransport("smtp");
            transport.connect(HOST, username, password);
            transport.sendMessage(mail, mail.getAllRecipients());
            transport.close();
        } catch (MessagingException mex) {
            logger.log(Level.SEVERE, mex.getLocalizedMessage());
        }
    }

    //TODO Проверить уникальность сообщение по его содержимому.
    @Override
    protected ua.edu.nuos.jeetraining2012.automator.core.vo.message.Message executeReceiveMessage(MessageSource source) {
        try {
            Message message = new Message();
            Store store = session.getStore();
            store.connect(HOST, username, password);
            Folder inbox = store.getFolder("Inbox");
            inbox.open(1);
            SearchTerm searchTerm = new BodyTerm(source.getSource());
            javax.mail.Message[] search = inbox.search(searchTerm);
            Multipart mp = (Multipart) search[0].getContent();
            for (int i = 0; i < mp.getCount(); i++) {
            }
            message.setSubject(search[0].getSubject());
            message.setText(mp.toString());
            return message;
        } catch (NoSuchProviderException e1) {
            System.out.println(e1.getMessage());
            return null;
        } catch (MessagingException e1) {
            System.out.println(e1.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return null;
        }
    }
}
